import 'package:flutter/material.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/student/ProfileStudent.dart';
import 'package:ichinesereader/pages/parent/studentDetails.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

// ignore: must_be_immutable
class ParentChildrenDataGrid extends StatelessWidget {
  ParentChildrenDataGrid(this.students);

  List<ProfileStudent> students;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();
  final UserController _userController = Get.find();

  @override
  Widget build(BuildContext context) {
    Log.debug('build parent chidlren data grid');
    return Container(
      margin: EdgeInsets.fromLTRB(0.0, 3.0, 12.0, 3.0),
      child: _buildDataGrid(),
    );
  }

  Container _buildDataGrid() {
    return Container(
      decoration: BoxDecoration(
        color: Get.isDarkMode
            ? AppTheme.colors.darkTheme1
            : Colors.white.withOpacity(0.2),
        borderRadius: BorderRadius.circular(6.0),
      ),
      child: Container(
        padding: EdgeInsets.all(30.0),
        margin: EdgeInsets.all(12.0),
        decoration: BoxDecoration(
            color: Get.isDarkMode
                ? AppTheme.colors.darkTheme2
                : Colors.white.withOpacity(0.9),
            borderRadius: BorderRadius.circular(3.0)),
        child: SfDataGrid(
          source: StudentsDataGridSource(items: students),
          onQueryRowHeight: (row) {
            return row.rowIndex == 0 ? 50.0 : 49.0;
          },
          //设置表头高度
          showCheckboxColumn: false,
          allowFiltering: true,
          checkboxColumnSettings: Get.isDarkMode
              ? DataGridCheckboxColumnSettings(
                  backgroundColor: Color(0xff0a0e21),
                )
              : DataGridCheckboxColumnSettings(
                  backgroundColor: Colors.blue[50]),
          allowSorting: true,
          allowTriStateSorting: true,
          allowSwiping: true,
          controller: _dataGridController,
          selectionMode: SelectionMode.none,
          navigationMode: GridNavigationMode.row,
          endSwipeActionsBuilder:
              (BuildContext context, DataGridRow row, int rowIndex) {
            return GestureDetector(
                onTap: () {
                  var userName = row
                      .getCells()
                      .where((element) => element.columnName == 'UserName')
                      .first
                      .value;
                  _userController.unlinkChild(userName).then((statusMessage) {
                    if (statusMessage.status == 1000) {
                      Future.delayed(Duration(milliseconds: 1200), (() {
                        Get.snackbar('Message'.tr, 'Successfully unlinked'.tr,
                            backgroundColor: Theme.of(context).primaryColor,
                            colorText: Theme.of(context).primaryColorLight,
                            snackPosition: SnackPosition.BOTTOM);
                      }));
                      _userController.getProfile();
                    } else {
                      Future.delayed(Duration(milliseconds: 1200), (() {
                        Get.snackbar('Message'.tr,
                            'Failed to unlink, please try again later.'.tr,
                            backgroundColor: Theme.of(context).primaryColor,
                            colorText: Theme.of(context).primaryColorLight,
                            snackPosition: SnackPosition.BOTTOM);
                      }));
                    }
                  });
                },
                child: Container(
                    color: Colors.redAccent,
                    child: Center(
                      child: Icon(Icons.delete),
                    )));
          },

          columns: <GridColumn>[
            GridColumn(
              width: 180,
              columnName: 'FirstName',
              label: buildDataGridColumnLabel('FirstName'),
            ),
            GridColumn(
              columnName: 'LastName',
              //allowFiltering: false,
              width: 180,
              label: buildDataGridColumnLabel('LastName'),
            ),
            GridColumn(
              columnName: 'UserName',
              //allowFiltering: false,
              width: 180,
              label: buildDataGridColumnLabel('UserName'),
            ),
            GridColumn(
              columnName: 'LinkDate',
              width: 180,
              label: buildDataGridColumnLabel('LinkDate'),
            ),
            GridColumn(
              columnName: 'Profile',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Profile'),
            ),
          ],
        ),
      ),
    );
  }
}

class StudentsDataGridSource extends DataGridSource {
  StudentsDataGridSource({required List<ProfileStudent> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'FirstName', value: dataGridRow.firstName),
              DataGridCell<String>(
                  columnName: 'LastName', value: dataGridRow.lastName),
              DataGridCell<String>(
                  columnName: 'UserName', value: dataGridRow.userName),
              DataGridCell<int>(
                  columnName: 'LinkDate', value: dataGridRow.linkTime),
              DataGridCell<ProfileStudent>(
                  columnName: 'Profile', value: dataGridRow),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'LinkDate') {
            if (dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    DateFormat('yyyy-MM-dd kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall?.copyWith(
                        color: Get.isDarkMode
                            ? Get.theme.primaryColorDark
                            : Colors.blueGrey),
                  ));
            } else {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    ' - ',
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall?.copyWith(
                        color: Get.isDarkMode
                            ? Get.theme.primaryColorDark
                            : Colors.blueGrey),
                  ));
            }
          } else if (dataGridCell.columnName == 'UserName') {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                  onTap: () {
                    var profile = row
                        .getCells()
                        .where((element) => element.columnName == 'Profile')
                        .first
                        .value;
                    Get.to(() => StudentProfileSettingsForParent(
                          studentItem: profile,
                        ));
                  },
                  child: Text(
                    dataGridCell.value.toString(),
                    style: Get.textTheme.bodySmall?.copyWith(
                        color: Get.isDarkMode
                            ? Get.theme.primaryColorDark
                            : Colors.blueGrey),
                    overflow: TextOverflow.fade,
                  ),
                ));
          } else {
            return Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  softWrap: true,
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall?.copyWith(
                      color: Get.isDarkMode
                          ? Get.theme.primaryColorDark
                          : Colors.blueGrey),
                ));
          }
        }).toList());
  }
}
